package com.example.demo.mq;

import java.util.HashMap;
import java.util.Map;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class QueueConfig {

	@Autowired
	private AmqpAdmin amqpAdmin;

	// 定时交换器
	@Value("${queueConfig.delayExchangeName}")
	private String delayExchange;

	// 定时队列
	@Value("${queueConfig.delayQueueName}")
	private String delayQueue;

	// 创建交换机作用----普通队列使用
	@Value("${queueConfig.generalExchangeName}")
	private String generalExchange;

	@Value("${queueConfig.generalQueueName}")
	private String generalQueue;

	@Bean
	public DirectExchange createDirectExchange() {

//	

//
//		// 创建队列
//		amqpAdmin.declareQueue(new Queue(generalQueue));
//
//		// 创建绑定规则
//		amqpAdmin.declareBinding(new Binding(generalQueue, Binding.DestinationType.QUEUE, generalExchange, null, null));
		// 创建交换器
		return new DirectExchange(generalExchange);

	}

	/**
	 * 创建定时交换机
	 * 
	 * @return
	 */
	@Bean
	public CustomExchange delayExchange() {

		Map<String, Object> args = new HashMap<>();

		args.put("x-delayed-type", "direct");

		System.out.println("==================================================");
		System.out.println("交换机---------------------->：" + delayExchange);
		System.out.println("==================================================");
		// return new CustomExchange("test_exchange", "x-delayed-message", true, false,
		// args);
		return new CustomExchange(delayExchange, "x-delayed-message", true, false, args);
	}

	/**
	 * 创建定时队列
	 * 
	 * @return
	 */
	@Bean
	public Queue delayQueue() {

		System.out.println("==================================================");
		System.out.println("队列---------------------->：" + delayQueue);
		System.out.println("==================================================");

		Queue newDelayQueueName = new Queue(delayQueue, true);

		return newDelayQueueName;
	}

	@Bean
	public Queue generalQueue() {

		Queue newGeneralQueue = new Queue(generalQueue, true);

		return newGeneralQueue;

	}

	@Bean
	public Binding generalBinding() {

		// return
		// BindingBuilder.bind(generalQueue()).to(createDirectExchange()).with(generalQueue).;
		return BindingBuilder.bind(generalQueue()).to(createDirectExchange()).with(generalQueue);
	}

	/**
	 * 定时交换机绑定定时队列
	 * 
	 * @return
	 */
	@Bean
	public Binding delayBinding() {
		return BindingBuilder.bind(delayQueue()).to(delayExchange()).with(delayQueue).noargs();
	}

}